import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:dio/dio.dart';

import '../models/dateline_event.dart';
import '../services/dateline_service.dart';
import '../services/dateline_type_service.dart';

/// 日历类型服务提供者
final datelineTypeServiceProvider = Provider<DateLineTypeService>((ref) {
  // 创建用于日历类型API的Dio实例
  final dio = Dio(BaseOptions(
    baseUrl: 'http://10.0.2.2:9092',
    connectTimeout: const Duration(seconds: 10),
    receiveTimeout: const Duration(seconds: 10),
  ));
  
  return DateLineTypeService(dio);
});

/// 日历事件类型列表提供者
final datelineTypesProvider = FutureProvider<List<DatelineEventType>>((ref) async {
  final typeService = ref.read(datelineTypeServiceProvider);
  return await typeService.getAllDateLineTypes();
});

/// 时间线事件列表状态提供者
final datelineEventsProvider = StateNotifierProvider<DatelineEventsNotifier, List<DatelineEvent>>((ref) {
  final datelineService = ref.read(datelineServiceProvider);
  return DatelineEventsNotifier(datelineService);
});

/// 选中日期的时间线事件提供者
final selectedDateDatelineEventsProvider = Provider.family<List<DatelineEvent>, DateTime>((ref, date) {
  final allEvents = ref.watch(datelineEventsProvider);
  
  // 过滤出选中日期的事件
  return allEvents.where((event) {
    final eventDate = event.eventTime;
    return eventDate.year == date.year &&
           eventDate.month == date.month &&
           eventDate.day == date.day;
  }).toList();
});

/// 按事件类型过滤的时间线事件提供者（从本地缓存过滤）
final eventTypeFilteredDatelineEventsProvider = Provider.family<List<DatelineEvent>, DatelineEventType?>((ref, eventType) {
  final allEvents = ref.watch(datelineEventsProvider);
  
  if (eventType == null) {
    return allEvents;
  }
  
  return allEvents.where((event) => event.eventType == eventType).toList();
});

/// 按事件类型从接口加载的时间线事件提供者
final datelineEventsByTypeProvider = FutureProvider.family<List<DatelineEvent>, DatelineEventType?>((ref, eventType) async {
  final datelineService = ref.read(datelineServiceProvider);
  
  if (eventType == null) {
    // 如果是全部，则加载所有事件
    return await datelineService.getAllEvents();
  }
  
  // 根据事件类型从接口加载数据
  return await datelineService.getEventsByType(eventType);
});

/// 时间线事件加载状态提供者
final datelineEventsLoadingProvider = StateProvider<bool>((ref) => false);

/// 时间线事件错误状态提供者
final datelineEventsErrorProvider = StateProvider<String?>((ref) => null);

/// 时间线事件状态管理器
class DatelineEventsNotifier extends StateNotifier<List<DatelineEvent>> {
  final DatelineService _datelineService;

  DatelineEventsNotifier(this._datelineService) : super([]) {
    // 初始化时加载所有事件
    loadAllEvents();
  }

  /// 加载所有时间线事件
  Future<void> loadAllEvents() async {
    try {
      final events = await _datelineService.getAllEvents();
      state = events;
    } catch (e) {
      print('加载时间线事件失败: $e');
      // 可以通过其他 provider 来管理错误状态
    }
  }

  /// 添加新的时间线事件
  Future<DatelineEvent?> addEvent(DatelineEvent event) async {
    try {
      final createdEvent = await _datelineService.createEvent(event);
      if (createdEvent != null) {
        // 将新事件添加到状态中
        state = [...state, createdEvent];
        return createdEvent;
      }
      return null;
    } catch (e) {
      print('添加时间线事件失败: $e');
      return null;
    }
  }

  /// 更新时间线事件
  Future<DatelineEvent?> updateEvent(DatelineEvent event) async {
    try {
      final updatedEvent = await _datelineService.updateEvent(event);
      if (updatedEvent != null) {
        // 更新状态中的事件
        state = state.map((e) => e.id == updatedEvent.id ? updatedEvent : e).toList();
        return updatedEvent;
      }
      return null;
    } catch (e) {
      print('更新时间线事件失败: $e');
      return null;
    }
  }

  /// 删除时间线事件
  Future<bool> removeEvent(String eventId) async {
    try {
      final success = await _datelineService.deleteEvent(eventId);
      if (success) {
        // 从状态中移除事件
        state = state.where((e) => e.id != eventId).toList();
        return true;
      }
      return false;
    } catch (e) {
      print('删除时间线事件失败: $e');
      return false;
    }
  }

  /// 根据日期获取时间线事件
  List<DatelineEvent> getEventsForDay(DateTime date) {
    return state.where((event) {
      final eventDate = event.eventTime;
      return eventDate.year == date.year &&
             eventDate.month == date.month &&
             eventDate.day == date.day;
    }).toList();
  }

  /// 根据日期范围获取时间线事件
  List<DatelineEvent> getEventsForDateRange(DateTime startDate, DateTime endDate) {
    return state.where((event) {
      final eventDate = event.eventTime;
      return eventDate.isAfter(startDate.subtract(const Duration(days: 1))) &&
             eventDate.isBefore(endDate.add(const Duration(days: 1)));
    }).toList();
  }

  /// 根据事件类型获取时间线事件
  List<DatelineEvent> getEventsByType(DatelineEventType eventType) {
    return state.where((event) => event.eventType == eventType).toList();
  }

  /// 搜索时间线事件
  List<DatelineEvent> searchEvents(String query) {
    if (query.isEmpty) {
      return state;
    }
    
    final lowerQuery = query.toLowerCase();
    return state.where((event) {
      return event.title.toLowerCase().contains(lowerQuery) ||
             (event.description?.toLowerCase().contains(lowerQuery) ?? false) ||
             (event.location?.toLowerCase().contains(lowerQuery) ?? false);
    }).toList();
  }

  /// 刷新时间线事件
  Future<void> refresh() async {
    await loadAllEvents();
  }

  /// 按时间排序事件（最新的在前）
  void sortEventsByTime({bool ascending = false}) {
    final sortedEvents = List<DatelineEvent>.from(state);
    sortedEvents.sort((a, b) {
      return ascending 
          ? a.eventTime.compareTo(b.eventTime)
          : b.eventTime.compareTo(a.eventTime);
    });
    state = sortedEvents;
  }

  /// 按事件类型分组
  Map<DatelineEventType, List<DatelineEvent>> groupEventsByType() {
    final Map<DatelineEventType, List<DatelineEvent>> groupedEvents = {};
    
    for (final event in state) {
      final eventType = event.eventType;
      if (groupedEvents[eventType] == null) {
        groupedEvents[eventType] = [];
      }
      groupedEvents[eventType]!.add(event);
    }
    
    return groupedEvents;
  }

  /// 按月份分组
  Map<String, List<DatelineEvent>> groupEventsByMonth() {
    final Map<String, List<DatelineEvent>> groupedEvents = {};
    
    for (final event in state) {
      final monthKey = '${event.eventTime.year}-${event.eventTime.month.toString().padLeft(2, '0')}';
      if (groupedEvents[monthKey] == null) {
        groupedEvents[monthKey] = [];
      }
      groupedEvents[monthKey]!.add(event);
    }
    
    return groupedEvents;
  }

  /// 获取统计信息
  Map<String, dynamic> getStatistics() {
    final totalEvents = state.length;
    final eventsByType = groupEventsByType();
    final eventsByMonth = groupEventsByMonth();
    
    // 计算最活跃的事件类型
    DatelineEventType? mostActiveType;
    int maxCount = 0;
    eventsByType.forEach((type, events) {
      if (events.length > maxCount) {
        maxCount = events.length;
        mostActiveType = type;
      }
    });
    
    // 计算最活跃的月份
    String? mostActiveMonth;
    int maxMonthCount = 0;
    eventsByMonth.forEach((month, events) {
      if (events.length > maxMonthCount) {
        maxMonthCount = events.length;
        mostActiveMonth = month;
      }
    });
    
    return {
      'totalEvents': totalEvents,
      'eventsByType': eventsByType.map((type, events) => MapEntry(type.displayName, events.length)),
      'eventsByMonth': eventsByMonth.map((month, events) => MapEntry(month, events.length)),
      'mostActiveType': mostActiveType?.displayName,
      'mostActiveMonth': mostActiveMonth,
      'eventsWithPhotos': state.where((event) => event.photoUrls.isNotEmpty).length,
    };
  }
}